package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.CommunicationRecord;
import enum_var.SenderType;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.CommunicationService;
import service.impl.CommunicationServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/communication/*")
public class CommunicationServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final CommunicationService communicationService = new CommunicationServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || "/".equals(pathInfo)) {
                // 获取沟通记录列表
                Long applicationId = Long.parseLong(request.getParameter("applicationId"));
                List<CommunicationRecord> records = communicationService.getRecordsByApplicationId(applicationId);
                result.put("success", true);
                result.put("data", records);
            } else if (pathInfo.startsWith("/detail/")) {
                // 获取沟通记录详情
                Long recordId = Long.parseLong(pathInfo.substring(8));
                CommunicationRecord record = communicationService.getRecordById(recordId);
                
                if (record == null) {
                    throw new Exception("记录不存在");
                }
                
                result.put("success", true);
                result.put("data", record);
            } else {
                throw new Exception("无效的请求路径");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            // 解析请求参数
            Long applicationId = Long.parseLong(request.getParameter("applicationId"));
            String content = request.getParameter("content");
            SenderType senderType = SenderType.valueOf(request.getParameter("senderType"));

            // 创建沟通记录
            CommunicationRecord record = new CommunicationRecord();
            record.setApplicationId(applicationId);
            record.setSenderId(userId);
            record.setSenderType(senderType);
            record.setContent(content);
            record.setSendTime(LocalDateTime.now());

            // 保存记录
            communicationService.createRecord(record);

            result.put("success", true);
            result.put("message", "消息发送成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || !pathInfo.startsWith("/update/")) {
                throw new Exception("无效的请求路径");
            }

            Long recordId = Long.parseLong(pathInfo.substring(8));
            String content = request.getParameter("content");

            CommunicationRecord record = communicationService.getRecordById(recordId);
            if (record == null) {
                throw new Exception("记录不存在");
            }

            // 只有发送者可以修改自己的消息
            if (!record.getSenderId().equals(userId)) {
                throw new Exception("权限不足");
            }

            // 更新记录
            record.setContent(content);
            record.setUpdateTime(LocalDateTime.now());

            communicationService.updateRecord(record);

            result.put("success", true);
            result.put("message", "消息更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            Long userId = (Long) session.getAttribute("userId");
            String role = (String) session.getAttribute("role");

            if (userId == null) {
                throw new Exception("请先登录");
            }

            if (pathInfo == null || !pathInfo.startsWith("/delete/")) {
                throw new Exception("无效的请求路径");
            }

            Long recordId = Long.parseLong(pathInfo.substring(8));
            
            CommunicationRecord record = communicationService.getRecordById(recordId);
            if (record == null) {
                throw new Exception("记录不存在");
            }

            // 只有发送者和客服可以删除消息
            if (!record.getSenderId().equals(userId) && !"CUSTOMER_SERVICE".equals(role)) {
                throw new Exception("权限不足");
            }

            communicationService.deleteRecord(recordId);

            result.put("success", true);
            result.put("message", "消息删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }
}
